package cn.iune.web.security.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import com.alibaba.fastjson.JSONObject;

import cn.iune.common.response.ResultData;


//shiro授权检查过滤器（自定义），好像不需要也可以解决问题
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

	/*
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		// TODO Auto-generated method stub
		return super.onAccessDenied(request, response, mappedValue);
	}
	*/

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		//return super.onAccessDenied(request, response);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();
        
        String projectName = httpServletRequest.getServletContext().getContextPath();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    	System.out.println("shiro.MyPermissionsAuthorizationFilter.onAccessDenied-->>"+uri);
        //判断是否为ajax
        if (isAjax(request)) {
        	System.out.println("MyPermissionsAuthorizationFilter.onAccessDenied-->>ajax请求-->>"+uri);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            ResultData resultData = new ResultData();
            resultData.setCode(-998);
            resultData.setMsg("授权认证失效，或者未授权PERMS!");
            httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
        } else {
        	System.out.println("MyPermissionsAuthorizationFilter.onAccessDenied-->>非ajax请求-->>"+uri);
            //saveRequestAndRedirectToLogin(request, response);
            /**
             * @Mark 非ajax请求重定向为登录页面
             */
            httpServletResponse.sendRedirect(projectName + this.getLoginUrl());
        }
        return false;
	}

    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        System.out.println("MyPermissionsAuthorizationFilter.isAjax-->>"+header);
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
    


}
